<template>
  <div id="tags-view-container" class="tags-view-container">
    <div class="tags-wrapper" ref="tagsWrapperRef">
      <el-tag
        v-for="tag in visitedViews"
        :key="tag.path"
        :closable="tag.path !== '/index'"
        :type="isActive(tag.path) ? 'primary' : 'info'"
        class="tag-item"
        @close="handleClose(tag)"
        @click="handleClick(tag)"
      >
        {{ tag.title }}
      </el-tag>
    </div>
  </div>
</template>

<script setup lang="ts">
import tagsViewStore, { type TagView } from '@/stores/modules/app'

const router = useRouter()
const route = useRoute()
const tagsWrapperRef = ref<HTMLElement>()

const store = tagsViewStore()
const visitedViews = computed(() => store.getVisitedViews)

// 判断标签是否激活
const isActive = (path: string) => {
  return route.path === path
}

// 点击标签跳转
const handleClick = (tag: TagView) => {
  router.push(tag.fullPath)
}

// 关闭标签
const handleClose = (tag: TagView) => {
  // 主页标签不可关闭
  if (tag.path === '/index') {
    return
  }

  // 如果关闭的是当前页面，先找到跳转目标
  const isCurrentTag = isActive(tag.path)
  let targetTag: TagView | undefined = undefined

  if (isCurrentTag) {
    // 找到当前标签的索引
    const currentIndex = visitedViews.value.findIndex((v) => v.path === tag.path)
    // 如果还有标签，优先跳转到上一个标签，如果没有上一个则跳转到下一个
    if (visitedViews.value.length > 1) {
      const targetIndex = currentIndex > 0 ? currentIndex - 1 : currentIndex + 1
      targetTag = visitedViews.value[targetIndex]
    } else {
      // 如果没有其他标签了，跳转到主页
      targetTag = visitedViews.value.find((v) => v.path === '/index') || undefined
    }
  }

  // 删除标签
  store.delView(tag)

  // 如果关闭的是当前页面，跳转到目标标签
  if (isCurrentTag && targetTag) {
    router.push(targetTag.fullPath)
  }
}

// 监听路由变化，添加或移除标签（addView 内部会处理 isTag 逻辑）
watch(
  () => route.path,
  () => {
    store.addView(route)
  },
  { immediate: true },
)
</script>

<style lang="scss" scoped>
.tags-view-container {
  height: 34px;
  width: 100%;
  background: #fff;
  border-bottom: 1px solid #d8dce5;
  box-shadow:
    0 1px 3px 0 rgba(0, 0, 0, 0.12),
    0 0 3px 0 rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.tags-wrapper {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 8px;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;

  // 自定义滚动条样式
  &::-webkit-scrollbar {
    height: 4px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 2px;

    &:hover {
      background: #a8abb2;
    }
  }
}

.tag-item {
  margin-right: 8px;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s;

  &:hover {
    opacity: 0.8;
  }

  &:last-child {
    margin-right: 0;
  }
}
</style>
